/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.zzzzzz.app.account.security;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.Sha256CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.zzzzzz.app.account.NoSuchUserException;
import com.zzzzzz.app.account.model.bo.UserRoleBo;
import com.zzzzzz.app.account.model.po.Role;
import com.zzzzzz.app.account.model.po.User;
import com.zzzzzz.app.account.service.UserManager;
import com.zzzzzz.app.account.service.UserRoleManager;

/**
 * <p>Because a Realm is really just a security-specific DAO, we could have just made Hibernate calls directly
 * in the implementation and named it a 'HibernateRealm' or something similar.</p>
 *
 * <p>But we've decided to make the calls to the database using a UserDAO, since a DAO would be used in other areas
 * of a 'real' application in addition to here. We felt it better to use that same DAO to show code re-use.</p>
 */
@Component
public class ShiroDbRealm extends AuthorizingRealm {

	@Resource
	private UserManager userManager;

	@Resource
	private UserRoleManager userRoleManager;

    public ShiroDbRealm() {
        setName("DbRealm"); //This name must match the name in the User class's getPrincipals() method
        setCredentialsMatcher(new Sha256CredentialsMatcher());
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = null;
		try {
			user = userManager.findByEmail(token.getUsername());
		} catch (Exception e) {
			if(e instanceof NoSuchUserException) {
				logger.error(e.getMessage());
			}else {
				logger.error(e.getMessage(), e);
			}
		}
        if( user != null ) {
            return new SimpleAuthenticationInfo(user.getUserId(), user.getPassword(), getName());
        } else {
            return null;
        }
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Long userId = (Long) principals.fromRealm(getName()).iterator().next();
        UserRoleBo userRoleBo = null;
		try {
			userRoleBo = userRoleManager.findByUserId(userId);
		} catch (Exception e) {
			if(e instanceof NoSuchUserException) {
				logger.error("No User exists with the primary key " + userId);
			}else {
				logger.error(e.getMessage(), e);
			}
		}
        
        if(userRoleBo != null){
        	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    		Set<String>	roleNames = new HashSet<String>();
        	List<Role> roles = userRoleBo.getRoleList();
        	for(Role r : roles) {
        		roleNames.add(r.getName());
        	}
        	info.setRoles(roleNames);
        	
			return info;
        }else{
        	return null;
        }
    }

	private static Logger logger = Logger.getLogger(ShiroDbRealm.class);

}

